package pl.edu.romanow.util

import io.Source
import net.liftweb.common.{Empty, Full, Box}
import java.net.{URL, HttpURLConnection}

/**
 * Created by IntelliJ IDEA.
 * User: jar
 * Date: 25.03.12
 * Time: 12:20
 * To change this template use File | Settings | File Templates.
 */

object HTTPUtil {

  def readFromGetRequest(urlS: String): (Int, Box[String]) = {
    val url = new URL(urlS)
    val connection: HttpURLConnection = url.openConnection().asInstanceOf[HttpURLConnection]
    connection.setRequestMethod("GET")
    connection.setDoInput(true)
    connection.setRequestProperty("Content-type", "text/plain")

    connection.getResponseCode match {
      case ResponseCodes.OK => (connection.getResponseCode, Full(Source.fromInputStream(connection.getInputStream).mkString))
      case _ => connection.getErrorStream match {
        case null => (connection.getResponseCode, Empty)
        case st => (connection.getResponseCode, Full(Source.fromInputStream(st).mkString))
      }
    }
  }


}

object ResponseCodes {
  val OK = 200
  val CREATED = 201
  val BAD_REQUEST = 400
  val UNAUTHORIZED = 401
  val FORBIDDEN = 403
  val NOT_FOUND = 404
  val ENHANCE_YOUR_CALM = 420 // Twitter-specific
  val INTERNAL_SERVER_ERROR = 500
  val BAD_GATEWAY = 502
  val SERVICE_UNAVAILABLE = 503
}

